import javax.swing.*;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;

/**
 * @author gcl
 * @date 2022/10/26 15:30
 */
public class TsMerge {

    final static String HELP_TEXT = "/**\n" +
            " * ts文件合并\n" +
            " * copy /b *.ts new.ts\n" +
            " * 直接转\n" +
            " * ffmpeg -i new.ts -c copy -map 0:v -map 0:a output.mp4\n" +
            " * 指定音频流（一般用这个）\n" +
            " * ffmpeg -i new.ts -c copy -map 0:v -map 0:a -bsf:a aac_adtstoasc output.mp4\n" +
            " * 重编码视频\n" +
            " * ffmpeg -y -i new.ts -c:v libx264 -c:a copy -bsf:a aac_adtstoasc output.mp4\n" +
            " */";

    final static String NEW_NAME = "anorak";

    public static void main(String[] args) {
        System.out.println(HELP_TEXT);
        File m3u8File = chooseSomeThing(JFileChooser.FILES_ONLY);
        File tsFile = chooseSomeThing(JFileChooser.DIRECTORIES_ONLY);
        try (Scanner sc = new Scanner(new FileReader(m3u8File))) {
            int a = 1;
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                if ( !line.startsWith("#") ){
                    File ts = new File(tsFile,line.substring(line.lastIndexOf("/")+1));
                    File tsNew = new File(tsFile,NEW_NAME+String.format("%06d", a)+".ts" );
                    if (!ts.renameTo(tsNew)){
                        if (ts.exists()){
                            System.out.println(ts+" 重命名失败,序号 :"+a);
                        }else {
                            System.out.println(ts+" 文件未找到,序号 :"+a);
                        }
                    }
                    a++;
                }
            }
            System.out.println("Ts文件重命名已完成,请回车键退出程序!");
            System.in.read();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用于选择文件夹或文件
     * @param fileChooserType 请参考JFileChooser的参数
     * @return 获取到的文件对象
     */
    private static File chooseSomeThing(int fileChooserType ){
        JFileChooser fileChooser=new JFileChooser();
        if ( fileChooserType == JFileChooser.DIRECTORIES_ONLY ){
            fileChooser.setDialogTitle("请选择Ts文件所在的文件夹");
        } else if (fileChooserType == JFileChooser.FILES_ONLY) {
            fileChooser.setDialogTitle("请选择.m3u8文件");
        }
        fileChooser.setCurrentDirectory(new File("."));
        fileChooser.setFileSelectionMode(fileChooserType);
        int state = fileChooser.showOpenDialog(null);
        if ( state == JFileChooser.APPROVE_OPTION){
            return fileChooser.getSelectedFile();
        }
        throw new RuntimeException("文件获取失败");
    }

}
